package com.irenty.interview.datastructures;

/**
 * 1.1 Implement an algorithm to determine if a string has all unique
 * characters. What if you can not use additional data structures?
 * 
 * @author irenty
 * 
 */
public class UniqueCharacters {
	
	public static boolean isUnique(String str) {
		if (str == null)
			return false;
		if (str.length() < 2)
			return true;
		boolean[] chars = new boolean[256];
		for (int i = 0; i < str.length(); i++) {
			if (chars[str.charAt(i)]) {
				return false;
			}
			chars[str.charAt(i)] = true;
		}
		return true;
	}

	/**
	 * assuming only small letters
	 * @param str
	 * @return
	 */
	public static boolean isUniqueSmallLettersOnly(String str) {
		if (str == null)
			return false;
		if (str.length() < 2)
			return true;
		int charsFlags = 0;
		for (int i = 0; i < str.length(); i++) {
			int flagBit = 1 << (str.charAt(i) - 'a');
			if ((charsFlags & flagBit) > 0) {
				return false;
			}
			charsFlags |= flagBit;
		}
		return true;
	}
	
	/**
	 * No data store but slow O(n2)
	 * @param str
	 * @return
	 */
	public static boolean isUniqueNoDataStore(String str) {
		if (str == null)
			return false;
		if (str.length() < 2)
			return true;
		for (int i = 0; i < str.length() - 1; i++) {
			char c = str.charAt(i);
			for (int j = i + 1; j < str.length(); j++) {
				if (str.charAt(j) == c) {
					return false;
				}
			}
		}
		return true;
	}
	
	/*
	 * Another solution could be to sort all the letters O(n log(n)) and check for repeating letters.
	 */
}
